package com.polelink.testcenter.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

// ExcelUtils.java
@Slf4j
@Component
public class ExcelUtils {

    public String getStringCellValue(Cell cell) {
        if (cell == null) return null;

        try {
            return switch (cell.getCellType()) {
                case STRING -> StringUtils.isBlank(cell.getStringCellValue())?null:cell.getStringCellValue()
                        .trim()
                        .replaceAll("\\n", "");  // 新增换行符替换
                case NUMERIC -> String.valueOf((int) cell.getNumericCellValue());
                case BLANK -> null;
                default -> throw new IllegalStateException("Unexpected cell type: " + cell.getCellType());
            };
        } catch (Exception e) {
            log.warn("获取单元格字符串值失败", e);
            return null;
        }
    }
    
    public String getHexStringCellValue(Cell cell) {
        String value = getStringCellValue(cell);
        return value == null ? null : value.replace("0x", "").toUpperCase();
    }
    
    public double getNumericCellValue(Cell cell) {
        if (cell == null) return 0;
        
        try {
            return cell.getCellType() == CellType.NUMERIC ?
                   cell.getNumericCellValue() : 
                   Double.parseDouble(getStringCellValue(cell));
        } catch (Exception e) {
            log.warn("获取单元格数值失败", e);
            return 0;
        }
    }

    public Map<Integer, String> getControllerColumnMap(Sheet sheet) {
        Map<Integer, String> controllerMap = new LinkedHashMap<>();
        Row controllerRow = sheet.getRow(1); // 控制器名称在第2行

        // 从第5列开始处理（索引4）
        for (int col = 4; col < controllerRow.getLastCellNum(); col += 2) {
            String controllerName = getStringCellValue(controllerRow.getCell(col));
            if (controllerName != null && !controllerName.isBlank()) {
                controllerMap.put(col, controllerName);
            }
        }
        return controllerMap;
    }
}

